using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Spring.Aop;
using Spring.Aop.Framework;
using Spring.Objects.Factory;
using Spring.Objects.Factory.Config;

namespace Sedna.Core.Spring
{
    public class RegExAutoProxyPostProcessor: IObjectPostProcessor, IObjectFactoryAware, IInitializingObject
    {
        private IObjectFactory objectFactory;
        private string namePattern;
        private Regex nameRegex;
        private string advisorName;

        public string AdvisorName
        {
            set { advisorName = value; }
        }

        public string NamePattern
        {
            set { namePattern = value; }
        }

        public IObjectFactory ObjectFactory
        {
            set { objectFactory = value; }
        }

        public object PostProcessAfterInitialization(object instance, string name)
        {
            if (!nameRegex.IsMatch(name))
            {
                return instance;
            }

            ProxyFactory proxyFactory = new ProxyFactory(instance);
            proxyFactory.AddAdvisor((IAdvisor)objectFactory.GetObject(advisorName));
            return proxyFactory.GetProxy();
        }

        public object PostProcessBeforeInitialization(object instance, string name)
        {
            return instance;
        }

        public void AfterPropertiesSet()
        {
            nameRegex = new Regex(namePattern); 
        }

    }
}

